package com.longteng.lesson.view;

import com.longteng.lesson.po.User;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator
 * DATE : 2018/5/13
 * TIME : 15:12
 * PROJECT : java-lesson
 * PACKAGE : com.longteng.lesson
 *
 * @author <a href="mailto:taki@qq.com">Administrator</a>
 */
public class ExcelView extends AbstractXlsxView {
    @Override
    protected void buildExcelDocument(Map<String, Object> model, org.apache.poi.ss.usermodel.Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        /*
        * 下载的文件名
        * */
        String fileName = "UserList.xlsx";
        response.setCharacterEncoding("UTF-8");
        /*
        * response输出的数据类型
        * */
        response.setContentType("application/ms-excel");
        /*
        * 响应头
        * inline类型
        * */
        response.setHeader("Content-Disposition", "inline; filename="+new String(fileName.getBytes(),"iso8859-1"));
        OutputStream outputStream = response.getOutputStream();

        System.out.println(model.get("userList"));
        List<User> userList = (List<User>) model.get("userList");
        // 产生Excel表头
        Sheet sheet = workbook.createSheet("基本信息");
        Row header = sheet.createRow(0);
        // 产生标题列
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("名字");
        header.createCell(2).setCellValue("邮箱");
        header.createCell(3).setCellValue("密码");
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("mm/dd/yyyy"));
        int rowNumber = 1;
        for (User user : userList) {
            Row row = sheet.createRow(rowNumber++);
            // 产生标题列
            row.createCell(0).setCellValue(user.getCodeType());
            row.createCell(1).setCellValue(user.getUserName());
            row.createCell(2).setCellValue(user.getSex());
            row.createCell(3).setCellValue(user.getPassword());
        }
        workbook.write(outputStream);
        /*
        * 输出到页面的输出流
        * */
        outputStream.flush();
        outputStream.close();
    }
}
